//
//  WayneViewController.m
//  17Login
//
//  Created by 建 任 on 13-4-1.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "Config.h"
#import "Utility.h"
#import "RigisterViewController.h"
#import "DefineAction.h"
#import "JSON.h"
#import "AppDelegate.h"

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:123.0/255.0 green:123.0/255.0 blue:123.0/255.0 alpha:100];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(findPasswordAction:) normalImage:@"findpwd_01.png" lightedImage:@"findpwd_02.png" frame:CGRectMake(0, 0, 75, 31.5) title:nil tag:0]];
    //创建logo
    UIImageView *logo = [[UIImageView alloc]initWithFrame:CGRectMake(114, 22, 92, 100)];
    [logo setImage:[UIImage imageNamed:@"login_logo.png"]];
    [self.view addSubview:logo];
    
    //创建用户名背景
    UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(35, 140, 250, 36)];
    [userImg setImage:[UIImage imageNamed:@"login_fextfield_bg.png"]];
    [self.view addSubview:userImg];
    
    //创建用户名文本框
    self.userField = [[UITextField alloc] initWithFrame:CGRectMake(40, 140, 240, 36)];
    self.userField.placeholder=@"一起帐号";
    self.userField.delegate=self;
    self.userField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.userField.returnKeyType=UIReturnKeyNext;
    self.userField.clearButtonMode=UITextFieldViewModeWhileEditing;
    self.userField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    self.userField.backgroundColor=[UIColor  clearColor];
    self.userField.borderStyle=UITextBorderStyleNone;
    self.userField.textColor=[UIColor blackColor];
    self.userField.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    self.userField.autocorrectionType=UITextAutocorrectionTypeNo;
    [self.userField setBorderStyle:UITextBorderStyleNone];
    self.userField.returnKeyType = UIReturnKeyNext;
    self.userField.keyboardType=UIKeyboardTypeEmailAddress;
    [self.view addSubview:self.userField];

    
    //创建密码背景
    UIImageView *passImg = [[UIImageView alloc]initWithFrame:CGRectMake(35, 188, 250, 36)];
    [passImg setImage:[UIImage imageNamed:@"login_fextfield_bg.png"]];
    [self.view addSubview:passImg];
    
    //创建密码输入框
    self.passField = [[UITextField alloc] initWithFrame:CGRectMake(40, 188, 240, 36)];
    self.passField.placeholder=@"密码";
    self.passField.delegate=self;
    self.passField.keyboardType=UIKeyboardAppearanceDefault;
    self.passField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.passField.returnKeyType=UIReturnKeyNext;
    self.passField.clearButtonMode=UITextFieldViewModeWhileEditing;
    self.passField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    self.passField.backgroundColor=[UIColor  clearColor];
    self.passField.borderStyle=UITextBorderStyleNone;
    self.passField.textColor=[UIColor blackColor];
    self.passField.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    self.passField.autocorrectionType=UITextAutocorrectionTypeNo;
    [self.passField setBorderStyle:UITextBorderStyleNone];
    self.passField.returnKeyType = UIReturnKeySend;
    self.passField.secureTextEntry = YES;
    [self.view addSubview:self.passField];
    
    //创建注册按钮
    UIButton *resigeBut = [[UIButton alloc] initWithFrame:CGRectMake(36, 240, 122, 40)];
    [resigeBut setImage:[UIImage imageNamed:@"resige_1.png"] forState:UIControlStateNormal];
    [resigeBut setImage:[UIImage imageNamed:@"resige_2.png"] forState:UIControlStateHighlighted];
    resigeBut.adjustsImageWhenHighlighted = NO;
    [self.view addSubview:resigeBut];
    
    [resigeBut addTarget:self action:@selector(goRegister:) forControlEvents:UIControlEventTouchUpInside];
    
    //创建登录按钮
    UIButton *loginBut = [[UIButton alloc] initWithFrame:CGRectMake(162, 240, 122, 40)];
    [loginBut setImage:[UIImage imageNamed:@"login_1.png"] forState:UIControlStateNormal];
    [loginBut setImage:[UIImage imageNamed:@"login_2.png"] forState:UIControlStateHighlighted];
    loginBut.adjustsImageWhenHighlighted = NO;
    [self.view addSubview:loginBut];
    [loginBut addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    
    
	// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction)findPasswordAction:(id)sender{


}

-(IBAction)goRegister:(id)sender{
    RegisterViewController *reg=[[RegisterViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:reg animated:YES];
}

-(IBAction)login:(id)sender
{
    NSString *username = self.userField.text;
    NSString *password = self.passField.text;
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    if (username==nil||[username isEqualToString:@""]) {
        [Utility customAlertWithMsg:USERNAMEMSG1 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    if (![Utility ValidateEmail:username]) {
        [Utility customAlertWithMsg:USERNAMEMSG2 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    
	if (password==nil||[password isEqualToString:@""]||[password length]<3) {
        [Utility customAlertWithMsg:PASSWORDMSG1 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    //NSString *url=[NSString stringWithFormat:@"%@/%@?u.u1=%@&u.u3=%@&type=0",[Utility getServerUrl],LOGINACTION,username,password];
    //self.request=[[URLRequest alloc] initWithURL:url andDelegate:self];
      NSString *url=[NSString stringWithFormat:@"%@/%@?type=0",[Utility getServerUrl],LOGINACTION];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:[NSMutableDictionary dictionaryWithObjectsAndKeys:username,@"u.u1",password,@"u.u3", nil] andFile:nil];
    [self.request startLoadData];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField{
        CGRect rect=self.view.frame;
        rect.origin.y=-100;
        self.view.frame=rect;
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.userField) {
        [self.passField becomeFirstResponder];
    }else if(textField==self.passField) {
        CGRect rect=self.view.frame;
        rect.origin.y=0;
        self.view.frame=rect;
        [self.userField resignFirstResponder];
        [self.passField resignFirstResponder];
        [self login:nil];
    }
    return NO;
}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            NSDictionary *userdict=[result objectForKey:@"data"];
            if (userdict) {
                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                [user setObject:[userdict objectForKey:@"u0"] forKey:USERID];
                [user setObject:[userdict objectForKey:@"u1"] forKey:USERNAME];
                [user setObject:[userdict objectForKey:@"u2"] forKey:USERNICKNAME];
                [user setObject:self.passField.text forKey:USERPASSWORD];
                [user setObject:[userdict objectForKey:@"u6"] forKey:USERLOGO];
                [user setObject:[userdict objectForKey:@"u7"] forKey:USERINTRO];
                [user synchronize];
                AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
                [app popLoginViewController];
            }else{
                [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
            }
            
        }else{
            [Utility customAlertWithMsg:LOGINFAIL andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
     [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}




- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
